#人工智能NLP-Agent数字人项目-02-日程提醒任务工单V1.1-20250215
import abc
import sqlite3
import re
from typing import Any
from langchain.tools import BaseTool
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class MyTimer(BaseTool, abc.ABC):
    name: str = "MyTimer"
    description: str = ("用于设置日程。接受3个参数，格式为: HH:MM|YYYYYYY|事项内容，所用标点符号必须为标准的英文字符。"
                        "其中，'HH:MM' 表示时间（24小时制），'YYYYYYY' 表示循环规则（每位代表一天，从星期一至星期日，1为循环，0为不循环，"
                        "如'1000100'代表每周一和周五循环），'事项内容' 是提醒的具体内容。返回例子：15:15|0000000|提醒主人叫咖啡")
    uid: int = 0

    def __init__(self):
        super().__init__()
        self.initialize_database()

    def initialize_database(self):
        with self.get_db_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS timer (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    time TEXT NOT NULL,
                    repeat_rule TEXT NOT NULL,
                    content TEXT NOT NULL,
                    uid INTEGER NOT NULL
                )
            """)
            conn.commit()

    async def _arun(self, *args: Any, **kwargs: Any) -> Any:
        # 用例中没有用到 arun 不予具体实现
        pass

    def _run(self, para: str) -> str:
        # 拆分输入字符串
        parts = para.split("|")
        if len(parts) != 3:
            return f"输入格式错误，当前字符串{para} len:{len(parts)}。请按照 HH:MM|YYYYYYY|事项内容 格式提供参数，如：15:15|0000001|提醒主人叫咖啡。"

        time, repeat_rule, content = [part.strip("'") for part in parts]

        # 验证输入
        validation_errors = []
        if not self.validate_time(time):
            validation_errors.append("时间格式错误。请按照'HH:MM'格式提供时间。")
        if not self.validate_repeat_rule(repeat_rule):
            validation_errors.append("循环规则格式错误。请提供长度为7的0和1组成的字符串。")
        if not self.validate_content(content):
            validation_errors.append("事项内容必须为非空字符串。")

        if validation_errors:
            return "\n".join(validation_errors)

        # 数据库操作
        result = self.insert_into_database(time, repeat_rule, content)
        return result

    def insert_into_database(self, time: str, repeat_rule: str, content: str) -> str:
        try:
            with self.get_db_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("INSERT INTO timer (time, repeat_rule, content, uid) VALUES (?, ?, ?, ?)",
                               (time, repeat_rule, content, self.uid))
                conn.commit()
                return "日程设置成功"
        except sqlite3.Error as e:
            logging.error(f"数据库错误: {e}")
            return f"数据库错误: {e}"

    def validate_time(self, time: str) -> bool:
        return bool(re.match(r'^[0-2][0-9]:[0-5][0-9]$', time))

    def validate_repeat_rule(self, repeat_rule: str) -> bool:
        return bool(re.match(r'^[01]{7}$', repeat_rule))

    def validate_content(self, content: str) -> bool:
        return isinstance(content, str) and bool(content.strip())

    def get_db_connection(self):
        """上下文管理器，用于数据库连接"""
        conn = sqlite3.connect('timer.db')
        try:
            yield conn
        finally:
            conn.close()


if __name__ == "__main__":
    my_timer = MyTimer()
    result = my_timer._run("15:15|0000001|提醒主人叫咖啡")
    print(result)